const server=require("../../server/server.js");
Page({
    data:{
        products:[],
        params:{
            page:1,
            rows:4,
            typeId:-1
        },
        types:[],
        total:0,
        flag:true,
        init:false
    },
    onLoad(){
        this.loadProductList();
        this.loadTypeList();
    },
    loadProductList(){
        return server.loadProductList1(this.data.params)
            .then((data)=>{
                this.setData({
                    products:this.data.products.concat(data.rows),
                    total:data.total
                });
            })
            .catch((error)=>{
                console.log(error);   
            })
    },
    loadTypeList(){
        server.loadTypeList()
            .then((data)=>{
                // console.log(data);
                let all={
                    id:-1,
                    name:"全部",
                    imgUrl:"../../img/temp/all.png"
                }
                data.unshift(all);
                let temp=[];
                let size=Math.ceil(data.length/5);
                for(let i=0;i<size;i++){
                    temp.push(data.splice(0,5));
                }
                this.setData({
                    types:temp
                });
                // console.log(temp);               
            })
            .catch((error)=>{
                console.log(error);
            })
    },
    findByType({currentTarget:{dataset:{typeId}}}){
        this.setData({
            products:[],
            "params.typeId":typeId,
            "params.page":1

        });
        this.loadProductList();
    },
    onReachBottom(){
        this.setData({
            //触底显示加载图片
            init:true,   
        });
        let page=this.data.params.page+1;
        let rows=this.data.params.rows;
        let count=Math.ceil(this.data.total/rows);
        if(page>count){
            this.setData({
                //当页数大于总页数时将加载图片隐藏显示底线
                flag:false
            });
            return;
        }

        this.setData({
           "params.page":this.data.params.page+1
        });       
        setTimeout(()=>{
            this.loadProductList()
            .then(()=>{
                this.setData({
                    //数据请求完成后关闭加载图片
                    init:false
                });
            })
        },1000);
    }
})
